package bg.cinema_system.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bg.cinema_system.global.ConnectionJDBC;

public class UserInfoDAO {

	// Connect to DB and get the username
	public static String getUsername(long user_id) throws SQLException {
		// Get database connection
		Connection dbConnection = ConnectionJDBC.getConnection();

		if (dbConnection == null) {
			throw new SQLException(
					"Class UserInfoDAO: Can't get database connection");
		}

		String sqlStatement = "SELECT users.username FROM users WHERE users.user_id = ?";

		PreparedStatement ps = dbConnection.prepareStatement(sqlStatement);
		ps.setLong(1, user_id);

		// Get customer data from database
		ResultSet result = ps.executeQuery();

		String username = "";

		while (result.next()) {
			username = result.getString("username");
		}

		// Close all connections
		ps.close();
		result.close();
		dbConnection.close();

		return username;
	}

	// Connect to DB and get the user_id
	public static int getUserId(String username) throws SQLException {
		// Get database connection
		Connection dbConnection = ConnectionJDBC.getConnection();

		if (dbConnection == null) {
			throw new SQLException(
					"Class UserInfoDAO: Can't get database connection");
		}

		String sqlStatement = "SELECT users.user_id FROM users WHERE users.username = ?";

		PreparedStatement ps = dbConnection.prepareStatement(sqlStatement);
		ps.setString(1, username);

		// Get customer data from database
		ResultSet result = ps.executeQuery();

		int user_id = 0;

		while (result.next()) {
			user_id = result.getInt("user_id");
		}

		// Close all connections
		ps.close();
		result.close();
		dbConnection.close();

		return user_id;
	}
}
